#include <stdio.h>
#include <stdlib.h>

void AdjustDown(int* a, int n, int root)//向下调整
{
    int parent = root;
    int child = parent * 2 + 1;
    while (child < n)
    {
        if (child + 1 < n && a[child + 1] > a[child])//选出大的那个孩子
        {
            child++;
        }
        if (a[child] > a[parent])
        {
            int tmp = a[child];
            a[child] = a[parent];
            a[parent] = tmp;
            parent = child;
            child = parent * 2 + 1;
        }
        else
        {
            break;
        }
    }
}

int* smallestK(int* arr, int arrSize, int k, int* returnSize)
{
    *returnSize = k;
    if (k == 0)
        return NULL;
    int* retArr = (int*)malloc(sizeof(int) * k);
    int i = 0;
    for (i = 0; i < k; i++)
    {
        retArr[i] = arr[i];
    }
    //建K个数的大堆
    for (i = (k - 1 - 1) / 2; i >= 0; i--)
    {
        AdjustDown(retArr, k, i);
    }

    for (i = k; i < arrSize; i++)
    {
        if (arr[i] < retArr[0])
        {
            retArr[0] = arr[i];
            AdjustDown(retArr, k, 0);
        }
    }
    *returnSize = k;

    return retArr;
}

int main()
{
    // 测试数据
    int arr[] = { 1,3,5,7,2,4,6,8 };
    int arrSize = sizeof(arr) / sizeof(arr[0]);
    int k = 4;
    int returnSize;
    int i=0;
    // 调用 smallestK 函数
    int* result = smallestK(arr, arrSize, k, &returnSize);
    
    // 输出结果
    printf("The smallest %d elements are:\n", k);
    for ( i = 0; i < returnSize; i++) {
        printf("%d ", result[i]);
    }
    printf("\n");

    // 释放分配的内存
    free(result);
    return 0;
}
